package com.example.user

import android.view.View
import android.widget.Button
import android.widget.Toast
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.example.common.ARouterPath
import com.example.mvi_core.model.BaseActivity
import com.example.net.RetrofitFactory
import com.example.user.intent.UserIntent
import com.example.user.state.UserState
import com.example.user.viewmodel.UserViewModel
import com.google.android.material.textfield.TextInputEditText
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

@Route(path = ARouterPath.SP_JUMP_USER)
class LoginActivity : BaseActivity() {
    private var user: TextInputEditText?=null
    private var pas: TextInputEditText?=null
    private var login: Button?=null
    private var go_register: Button?=null
    private val viewModel by lazy{ UserViewModel() }
    override fun getLayoutRootView(): View? {
        return null
    }

    override fun getLayoutId(layout: Int): Int {
        return R.layout.activity_login
    }

    override fun initView() {
        super.initView()
        user=findViewById(R.id.user)
        pas=findViewById(R.id.pas)
        login=findViewById(R.id.login)
        go_register=findViewById(R.id.go_register)
        login?.setOnClickListener{
            lifecycleScope.launchWhenCreated {
                val u= user?.text.toString()
                val p=pas?.text.toString()
                viewModel.channel.send(UserIntent.Login(p,u))
            }
        }
        go_register?.setOnClickListener{
            ARouter.getInstance().build(ARouterPath.USER_JUMP_REGISTER).navigation()
        }
        lifecycleScope.launch{
            viewModel.observeState.collect {
                when(it){
                    is UserState.Loading->{
                        Toast.makeText(this@LoginActivity, "加载中", Toast.LENGTH_SHORT).show()
                    }
                    is UserState.Success->{
                        Toast.makeText(this@LoginActivity, "欢迎回来:${it.user.username}", Toast.LENGTH_SHORT).show()
                        RetrofitFactory.token=it.user.token
                        ARouter.getInstance().build(ARouterPath.USER_JUMP_MAIN).navigation()

                    }
                    is UserState.Failure ->{
                        Toast.makeText(this@LoginActivity, it.msg, Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }
    }

}